home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 5791 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.2 KB

  1. Path: druid.borland.com!usenet
  2. From: pete@borland.com (Pete Becker)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: aborting a constructor
  5. Date: 6 Feb 1996 20:47:02 GMT
  6. Organization: Borland International
  7. Message-ID: <4f8eo6$kik@druid.borland.com>
  8. References: <310DA3AB.6E32@tribeca.ios.com>
  9. NNTP-Posting-Host: pbecker.borland.com
  10. Mime-Version: 1.0
  11. Content-Type: Text/Plain; charset=ISO-8859-1
  12. X-Newsreader: WinVN 0.99.5
  13.  
  14. In article <310DA3AB.6E32@tribeca.ios.com>, leonardj@tribeca.ios.com says...
  15. >
  16. >In an earlier post, I asked how you use 'new' and a constructor in order to 
  17. deal with the 
  18. >following situation:
  19. >     You have a class, let's call it WindowClass, which, when it is 
  20. instantiated, does the 
  21. >following:
  22. >     1: It opens the file "filename", and gets its size.
  23. >     2: It allocates memory to hold "filename".
  24. >     3: It loads "filename" into that memory.
  25. >     4: It opens a window to display "filename".
  26. >     Now let's suppose that after it performs steps 1 thru 3 it cannot open 
  27. the window, what does it 
  28. >do? Furthermore, how do you code for this kind of situation in C++ in 
  29. general? My first thought was 
  30. >that the constructor should de-allocate all of the resources that it had 
  31. received so far. Then it 
  32. >should throw an exception. The question that I had was: what's going to 
  33. happen to the memory that 
  34. >was allocated for the object's data members? 
  35.  
  36. The compiler is responsible for generating code that will release allocated 
  37. memory when a constructor throws an exception.
  38.  
  39. >I nother words: what happens to an object if its 
  40. >constructor aborts?
  41.  
  42. This is an entirely different question, and its answer depends on what you 
  43. mean by "aborts".
  44.  
  45. > Is it automatically deleted? I still haven't really gotten to the bottom of 
  46. that 
  47. >question but I want to pose a possible solution to this dilemma and see if it 
  48. works. 
  49. >     Instead of the course of action described above, let's say that you have 
  50. the constructor 
  51. >execute the following statements:
  52. >
  53. >     delete this;
  54. >     throw(error);
  55. >
  56. >and you have the destructor of the class de-allocate the objects. I'd like to 
  57. know if this would 
  58. >work.
  59.  
  60. It would be a disaster. Think about what happens if you try to create one of 
  61. these things on the stack and the constructor fails.
  62.     -- Pete
  63.  
  64.